package gruppe5.dame.client.gui.Lobby;

import java.awt.Dimension;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;

import javax.swing.JPanel;
import javax.swing.JScrollPane;
/**
 * Liste mit allen Spielen auf dem Sever
 * @author kramerse
 *
 */
public class Gamelist extends JPanel implements MouseListener {
	
	/**
	 * serialVersionUID
	 */
	private static final long serialVersionUID = 4106539783474282573L;
	
	/**
	 * Tabelle
	 */
	GameListTable table;
	
	JScrollPane scrollPane;
	
	/**
	 * Testtabellen inhalt
	 */
	Object[][] data;
	
	/**
	 * Zeitpunkt des letzten Klicks
	 */
	private long lastClick;
	
	/**
	 * Lobby GUI
	 */
	LobbyGUI lobby;
	
	/**
	 * Konstruktor
	 * @param lobby
	 */
	public Gamelist(LobbyGUI lobby) {
		this.lobby = lobby;
		
		String[] columnNames = {"Spielname", "Spieler", "Ping"};
		table = new GameListTable(new Object [][] {{null, null, null}, {null, null, null}}, columnNames);
		table.addMouseListener(this);
		scrollPane = new JScrollPane(table);
		table.setFillsViewportHeight(true);
		scrollPane.setPreferredSize(new Dimension(510, 250));
		this.add(scrollPane);
	}
	
	/**
	 * Tabellen Inhalt setzten
	 * @param data
	 */
	public void setData(Object[][] data) {
		this.data = data;
		
		this.remove(scrollPane);

		String[] columnNames = {"Spielname", "Spieler", "Ping"};
		table = new GameListTable(data, columnNames);
		table.addMouseListener(this);
		scrollPane = new JScrollPane(table);
		table.setFillsViewportHeight(true);
		scrollPane.setPreferredSize(new Dimension(510, 250));
		this.add(scrollPane);
		
		this.revalidate();
	}
	
	@Override
	public void mouseClicked(MouseEvent arg0) {
	}
	
	@Override
	public void mouseEntered(MouseEvent arg0) {
	}
	
	@Override
	public void mouseExited(MouseEvent arg0) {
	}
	
	@Override
	public void mousePressed(MouseEvent arg0) {
	}
	
	@Override
	public void mouseReleased(MouseEvent arg0) {
		
		//Keine Aktion wenn auf ein eigenes Spiel geklickt wurde
		String username = lobby.getUsername();
		int row =  table.getSelectedRow();
		String gameName = (String) data[row][1];
		if(gameName.equals(username))
		{
			lobby.disableJoinAndInvite();
			return;
		}
			
		
		/*
		 * Pr�fung auf Dopelklick
		 */
		try {
			if(System.currentTimeMillis()-lastClick<500) {
				int var1 =  table.getSelectedRow();
				String var2 = (String) data[var1][0];
				lobby.joinGame(var2);
			}
		} catch (Exception e1) {
			e1.printStackTrace();
		}
		lastClick = System.currentTimeMillis();
		lobby.enableGamelist(true);
	}
	
	/**
	 * 
	 * @return ausgew&auml;hlter Benutzer
	 */
	public String getSelectedGameName() {
		int var1 =  table.getSelectedRow();
		String var2 = (String) data[var1][0];
		return var2;
	}
}